// This commands script file fined the versions of documents in a library and publishes them. It helps to find and publish files during massive code updates.
// Author: Sergei Snitko
// Blog: http://blog.cibpoint.ru/
// Last Update : 10/14/2015


console.clear();
var PublishDocuments = function (params) {
    var self = this;

    var params = params || {};
    var folder = params.folder || "";
    var listServerRelativeUrl = params.listServerRelativeUrl || "";
    var recursive = params.recursive ? 'Scope="Recursive"' : "";


    console = console || {};
    console.log = console.log || function () { };

    this.Publish = function () {
        if (listServerRelativeUrl) {
            EnsureScript('sp.js', typeof SP.ClientContext, function () {

                var clientContext = new SP.ClientContext();
                var web = clientContext.get_web();
                var list = web.getList(listServerRelativeUrl);
                clientContext.load(list);

                var camlQuery = new SP.CamlQuery();
                if (folder)
                    camlQuery.set_folderServerRelativeUrl(folder);

                camlQuery.set_viewXml('<View ' + recursive + '><Query><Where><Neq><FieldRef Name="_ModerationStatus" /><Value Type="ModStat">0</Value></Neq></Where></Query></View>');
                var itemsResults = list.getItems(camlQuery);
                self.items = clientContext.loadQuery(itemsResults);

                clientContext.executeQueryAsync(
                    function (data) {
                        for (var i = 0, ilen = self.items.length; i < ilen; i += 1) {
                            var item = self.items[i];
                            var values = item.get_fieldValues();

                            var file = web.getFileByServerRelativeUrl(item.get_fieldValues()["FileRef"]);
                            if (values["CheckedOutUserId"].get_lookupValue()) {
                                file.checkIn();
                            }
                            //console.log(item.get_fieldValues()["_ModerationStatus"]);
                            file.publish();
                        }

                        clientContext.executeQueryAsync(
                            function (data) {
                                console.log("published");
                            }, function (sender, args) {
                                self.AsyncError("FinishPublish", sender, args);
                            }
                        );
                    },
                    function (sender, args) {
                        self.AsyncError("StartPublish", sender, args);
                    }
                );
            });

        }
    };
    this.AsyncError = function (fName, sender, args) {
        console.log(fName + ': Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    };


    //Execute on creation
    this.Publish();
};



(function () {

    new PublishDocuments({
        folder: "/sites/site/_catalogs/masterpage/Display Templates/Search/",
        recursive: true,
        listServerRelativeUrl: "/sites/site/_catalogs/masterpage"
    })
})();